package com.dhcc.DRGsHosp.web.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openkoala.koala.commons.InvokeResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dhcc.DRGsHosp.facade.ReStartServiceFacade;

/**
 * @title		: ReStartService.java 
 * @description	: 重启分组服务
 * @author		: chl
 * @date		: 2017年3月9日
 * @version     : 2017
 * @copyright   : DHCC 
 */
@Controller("drgsHospWebController39")
@RequestMapping("/restartService")
public class ReStartServiceController {
	
	@Autowired
	ReStartServiceFacade reStartServiceFacade ;
	
	@ResponseBody
	@RequestMapping("/start")
	public InvokeResult start(HttpServletRequest request,HttpServletResponse response,String filePath ){
		String webRoot = request.getSession().getServletContext().getRealPath("/");
		String fileRealPath = webRoot + "WEB-INF\\restartService\\donghua.p12";
		if ((null == filePath || "".equals(filePath))) {
			return InvokeResult.failure("授权路径不能为空");
		}  
		boolean flag = reStartServiceFacade.isServiceStarted() ;
		if (flag) {
			if (!reStartServiceFacade.stop("cmd /c start " + webRoot
					+ "WEB-INF\\restartService\\stopDrgGroup.bat",filePath)) {
				return InvokeResult.failure("无法停止服务,请手动关停");
			}
		} 
		// 添加文件
		reStartServiceFacade.addFile(fileRealPath, filePath );
		Runtime rt = Runtime.getRuntime();
		Process ps = null;
		try {
			ps = rt.exec("cmd /c start " + webRoot
					+ "WEB-INF\\restartService\\startDrgGroup.bat");
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			ps.waitFor();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		ps.destroy();
		ps = null;
		int j = 0;
		// 等待服务成功启动
		while (j < 10) {
			if (reStartServiceFacade.isServiceStarted()) {
				break;
			} else {
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				j++;
			}
			if (j == 10) {
				reStartServiceFacade.deleteFile(filePath);
				return InvokeResult.failure("项目尚未启动");
			}
		}
		// 删除文件
		reStartServiceFacade.deleteFile(filePath);
		return InvokeResult.success("已成功重启");
	}
}
